package com.beemans.corekit.integration.metrics;

import android.content.Context;
import android.content.SharedPreferences;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public final class MetricsSpUtils {
    @Nullable
    private volatile SharedPreferences sharedPreferences;

    private MetricsSpUtils() {
        if (sharedPreferences == null) {
            synchronized (this) {
                if (sharedPreferences == null) {
                    final Context context = MetricsManager.getInstance().getContext();
                    if (context != null) {
                        sharedPreferences = context.getSharedPreferences(MetricsConstant.CACHE_NAME, Context.MODE_PRIVATE);
                    }
                }
            }
        }
    }

    private static final class Holder {
        private static final MetricsSpUtils INSTANCE = new MetricsSpUtils();
    }

    public static MetricsSpUtils getInstance() {
        return Holder.INSTANCE;
    }

    @Nullable
    public String getString(@NonNull String key, @Nullable String defValue) {
        final SharedPreferences preferences = sharedPreferences;
        if (preferences != null) {
            return preferences.getString(key, defValue);
        }
        return defValue;
    }

    public void putString(@NonNull String key, @Nullable String value) {
        final SharedPreferences preferences = sharedPreferences;
        if (preferences != null) {
            preferences.edit().putString(key, value).apply();
        }
    }

    public boolean getBoolean(@NonNull String key, boolean defValue) {
        final SharedPreferences preferences = sharedPreferences;
        if (preferences != null) {
            return preferences.getBoolean(key, defValue);
        }
        return defValue;
    }

    public void putBoolean(@NonNull String key, boolean value) {
        final SharedPreferences preferences = sharedPreferences;
        if (preferences != null) {
            preferences.edit().putBoolean(key, value).apply();
        }
    }
}